import axios from "axios";
import router from "./router";
import qs from "qs";
import { Message, MessageBox } from "element-ui";

//后台地址
// ECS云服务器地址 47.100.172.225
// 本机地址: 172.19.12.181
axios.defaults.baseURL = "http://localhost:9999";

//设置请求的超时时间
// 添加统一配置
const service = axios.create({
  // baseURL: "http://localhost:14777",
  timeout: 5000,
  headers: {
    "Content-Type": "application/json;charset=utf-8"
  }
});

// request 拦截器
service.interceptors.request.use(config => {
  config.headers["Authorization"] = localStorage.getItem("token");
  return config;
});

//  response  响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code == 200) {
      return response;
    } else {
      // console.log(res.msg);
      if (res.msg == "Bad credentials") {
        res.msg = "用户名或密码不正确";
      }
      // this.$message.error(res.msg ? "系统异常" : res.msg);
      Message({
        message: res.msg == null ? "系统异常,请联系管理员!" : res.msg,
        type: "error"
      });

      return Promise.reject("error");
    }
  },
  error => {
    if (error.response.data) {
      error.massage = error.response.data.msg;
    }

    if (error.response.status == 401) {
      router.push("/login");
    }
    // Element.$message.error(error, massage, { duration: 3000 });
    Message({
      message: error.message,
      type: "error",
      duration: 3000
    });

    return Promise.reject(error);
  }
);

export default service;
